package com.itheima.crm.web.action;

import java.util.Date;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.itheima.crm.domain.PageBean;
import com.itheima.crm.domain.SaleVisit;
import com.itheima.crm.service.SaleVisitService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 客户拜访记录的Action的类
 * 
 * @author Unicorn
 */
public class SaleVisitAction extends ActionSupport implements ModelDriven<SaleVisit> {
	private static final long serialVersionUID = 1L;
	// 模型驱动使用的对象
	private SaleVisit saleVisit = new SaleVisit();
	@Override
	public SaleVisit getModel() {
		return saleVisit;
	}
	
	// 利用注解的方式注入Service
	@Resource(name="saleVisitService")
	private SaleVisitService saleVisitService;
	
	// 分页参数
	private Integer currPage = 1;
	private Integer pageSize = 3;
	public void setCurrPage(Integer currPage) {
		if (currPage == null) {
			currPage = 1;
		}
		this.currPage = currPage;
	}
	public void setPageSize(Integer pageSize) {
		if (pageSize == null) {
			pageSize = 3;
		}
		this.pageSize = pageSize;
	}
	
	// 接收数据
	private Date visit_end_time;
	public Date getVisit_end_time() {
		return visit_end_time;
	}
	public void setVisit_end_time(Date visit_end_time) {
		this.visit_end_time = visit_end_time;
	}

	/**
	 * 查询拜访记录列表
	 * @return
	 */
	public String findAll() {
		// 创建离线条件查询对象
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SaleVisit.class);
		// 设置条件
		if (saleVisit.getVisit_time() != null) {
			detachedCriteria.add(Restrictions.ge("visit_time", saleVisit.getVisit_time()));
		}
		if (visit_end_time != null) {
			detachedCriteria.add(Restrictions.le("visit_time", visit_end_time));
		}
		
		// 调用业务层
		PageBean<SaleVisit> pageBean = saleVisitService.findByPage(detachedCriteria, currPage, pageSize);
		// 存入值栈
		ActionContext.getContext().getValueStack().push(pageBean);
		return "findAll";
	}
	
	/**
	 * 跳转到新增拜访记录的页面
	 * @return
	 */
	public String saveUI() {
		
		return "saveUI";
	}
	
	/**
	 * 保存客户拜访记录
	 * @return
	 */
	public String save() {
		// 调用业务层
		saleVisitService.save(saleVisit);
		return "saveSuccess";
	}
	
	/**
	 * 跳转到编辑页面
	 * @return
	 */
	public String edit() {
		// 根据id查询,跳转到修改页面回显数据
		saleVisit = saleVisitService.findById(saleVisit.getVisit_id());
		return "editSuccess";
	}
	
	/**
	 * 修改客户拜访记录
	 * @return
	 */
	public String update() {
		// 调用业务层
		saleVisitService.update(saleVisit);
		return "updateSuccess";
	}
	
	/**
	 * 删除客户拜访记录
	 * @return
	 */
	public String delete() {
		// 先查询,再删除
		saleVisit = saleVisitService.findById(saleVisit.getVisit_id());
		saleVisitService.delete(saleVisit);
		return "deleteSuccess";
	}
}
